package com.xxl.job.executor.service.jobhandler;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.dao.YhkqbMapper;
import com.xxl.job.executor.model.Yhkqb;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * XxlJob开发示例（Bean模式）
 *
 * 开发步骤： 1、任务开发：在Spring Bean实例中，开发Job方法； 2、注解配置：为Job方法添加注解
 * "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy =
 * "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。 3、执行日志：需要通过
 * "XxlJobHelper.log" 打印执行日志； 4、任务结果：默认任务结果为 "成功"
 * 状态，不需要主动设置；如有诉求，比如设置任务结果为失败，可以通过 "XxlJobHelper.handleFail/handleSuccess"
 * 自主设置任务结果；
 *
 * @author xuxueli 2019-12-11 21:52:51
 */
@Component
public class DataJobHandler {
	private static Logger logger = LoggerFactory.getLogger(DataJobHandler.class);

	/**
	 * 1、简单任务示例（Bean模式）
	 */
	@Resource
	YhkqbMapper yhkqbManager;
	@Resource // 自动注入，spring boot会帮我们实例化一个对象
	private JdbcTemplate commonDao; // 一个通过JDBC连接数据库的工具类，可以通过这个工具类对数据库进行增删改查
	
	@XxlJob("dataJobHandler")
	public String dataJobHandler() {
 		boolean istest = false;
		istest=false;
		int i=0;

		String rowid=null;
		Map json=null;
		try {
			//String sql = "SELECT zz_kqjltemp.* FROM zz_kqjltemp, tyzt WHERE tyzt.tybz = 'tempgen' AND zz_kqjltemp.kqsj >= tyzt.zhtqsj ORDER BY kqsj ASC";
			String sql="SELECT * FROM zz_test";

			List<Map> list = yhkqbManager.querySql(sql);
			if(list.size()==0)
			{
				XxlJobHelper.log("data size is zero.");

				return "_0";
			}
			String gh = "";
			String kqrq = "";
			String lastkqrq = "";
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			com.alibaba.fastjson.JSONArray banci = null;
			String lastgh = "";
			Yhkqb bean = null;
			int xh = 0;
			Date kqsj = null;
			Date dqsj = null;
			for ( i = 0; i < list.size(); i++) {

				 json = list.get(i);
				kqrq = json.get("kqrq").toString();
				gh = json.get("gh").toString();
				xh = Integer.parseInt(json.get("xh").toString());
				Object ob=json.get("leftsb");
				Date leftsb = (Date)json.get("leftsb");
				rowid=json.get("id_").toString();

				if (!lastkqrq.equals(kqrq) || !gh.equals(lastgh)) //日期和工號都相同，跳過
				{
					//存储上一条数据

					if (bean != null) {

//					if(!bean.getGh().equals(gh))
//					{
//						yhkqbManager.save(bean);
						if (bean.getId() != null) {
							yhkqbManager.updateByPrimaryKey(bean);
						}
						else {
							bean.setId(rowid+i);
							System.out.println("存储。。。"+i);
							yhkqbManager.insert(bean);
						}
//					}
					}

//				if(bean==null||!lastkqrq.equals(kqrq)||!bean.getGh().equals(gh))
					{

						List<Yhkqb> yhkqblist = yhkqbManager.query(gh, kqrq);

						boolean isInsert = true;

						if (yhkqblist.size() > 0) {
							bean = yhkqblist.get(0);

						} else {

							bean = new Yhkqb();
							bean.setBz(kqrq);
							bean.setGh(gh);
							bean.setBcid((String)json.get("bcid"));
							bean.setBc((String)json.get("bc"));
							bean.setXm((String)json.get("xm"));
							bean.setCjsj(new Date());
						}
					}
					lastgh = gh;
					lastkqrq = kqrq;
				}

				kqsj = (Date)json.get("kqsj");
				if (dqsj == null)
					dqsj = (Date)json.get("dqsj");
				else if (dqsj.getTime() < ((Date)json.get("dqsj")).getTime()) dqsj = (Date)json.get("dqsj");
//			Date leftsb=(Date)json.get("leftsb");
				Date leftxb = (Date)json.get("leftxb");
				Date leftsb2 = (Date)json.get("leftsb2");
				Date leftxb2 = (Date)json.get("leftxb2");
				//如数据已下班，则新上班为2
				if (kqsj.getTime() > leftsb.getTime() && kqsj.getTime() < leftxb.getTime()) {
					//上班时间，
					if (xh == 10) {
						bean.setSbdksj(kqsj);
						bean.setSbydksj((Date)json.get("sbdk2"));
						if (((Date)json.get("sbdk2")).getTime() > kqsj.getTime())
							bean.setSbdkzt("早到");
						else
							bean.setSbdkzt("迟到");

					} else {
						bean.setSbdksj2(kqsj);
						bean.setSbydksj2((Date)json.get("sbdk2"));
						if (((Date)json.get("sbdk2")).getTime() > kqsj.getTime())
							bean.setSbdkzt2("早到");
						else
							bean.setSbdkzt2("迟到");

					}


				} else if (kqsj.getTime() > leftsb2.getTime() && kqsj.getTime() < leftxb2.getTime()) {

					if (xh == 10) {

						bean.setXbdksj(kqsj);
						bean.setXbydksj((Date)json.get("xbdk2"));
						if (((Date)json.get("xbdk2")).getTime() > kqsj.getTime())

							bean.setXbdkzt("早退");
						else
							bean.setXbdkzt("晚退");
					} else {

						bean.setXbdksj2(kqsj);
						bean.setXbydksj2((Date)json.get("xbdk2"));
						if (((Date)json.get("xbdk2")).getTime() > kqsj.getTime())
							bean.setXbdkzt2("早退");
						else
							bean.setXbdkzt2("晚退");
					}


				}
			}
			//保存
			if (bean != null) {

//			JSONObject jj = new JSONObject();
//			jj.put("yhkqb", bean);
//			try {
//				AutoService.saveData("yhkqgl", "0", jj);
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			 yhkqbManager.save(bean);
				if (bean.getId() != null) {
					yhkqbManager.updateByPrimaryKey(bean);
				}else {
					bean.setId(rowid+i);
					System.out.println("存储。。。"+i);
					yhkqbManager.insert(bean);
				}
				commonDao.execute("update tyzt set zhtqsj='" + kqsj + "' where tybz='tempgen'");
			}
		}catch (Exception e)
		{
			e.printStackTrace();
			return rowid+"_"+0;
		}
		return rowid+"_"+i;
	}


 
	/**
	 * 5、生命周期任务示例：任务初始化与销毁时，支持自定义相关逻辑；
	 */
 

	public void init() {
		logger.info("init");
	}

	public void destroy() {
		logger.info("destory");
	}

}
